import React, {useState, useEffect} from 'react';
import {StyleSheet, View,Text, SectionList} from 'react-native';
import FilmItem from '../components/FilmItem';
import {getSoons} from '../services/film';
const Soon = props => {
  const [soons, setSoons] = useState([]);
  const [pagination, setPagination] = useState({});
  const [fresh, setFresh] = useState(false);
  const fillData = (data) => {
      let newData = [...soons];
     for(let i = 0;i < data.length;i++){
        let soon = newData.filter((item) => data[i].films.upDate == item.title)[0];
        
        if(soon){
            soon.data.push(data[i]);
        }else{
            newData.push({title:data[i].films.upDate,data:[data[i]]})
            // setSoons(...soons,{title:data[i].filmId.upDate,data:[data[i].filmId]});
           
        }
     }
     setSoons(newData);
  }
  useEffect(() => {
    (async ()=> {
      let data = await getSoons(1,3);
      console.log("data",data);
      // setSoons(data.rows);
      fillData(data.rows);
      setPagination(data);
    })()
    
  }, []);
  async function handleRefresh() {
    setFresh(true);
    let data = await getSoons(parseInt(pagination.current) + 1, pagination.size);
    // setSoons([...data.rows,...soons]);
    
    fillData(data.rows);
    setPagination(data);
    setFresh(false);
  }
  
  return (
    <View style={styles.container}>
      <SectionList
        refreshing={fresh}
        onRefresh={handleRefresh}
        sections={soons}
        renderItem={({item}) => <FilmItem film={item} isHot={false}></FilmItem>}
        renderSectionHeader={({ section: { title } }) => (
            <Text style={styles.header}>{title}</Text>
          )}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
});

export default Soon;
